<?
function str_limit($s, $n){
  if(strlen($s) > $n){
    $s = substr($s,0,$n) . " ...";
    return $s;
  }
}

function excerpt($text, $excerpt_length) {
    
  $text = str_replace(']]>', ']]&gt;', $text);
  $text = strip_tags($text);

  $excerpt_more = ' ...';

  $words = explode(' ', $text, $excerpt_length + 1);
  if (count($words) > $excerpt_length) {
    array_pop($words);
    $text = implode(' ', $words);
    $text = $text . $excerpt_more;
  }
  return $text;
}

function remote_file_size ($url){ 
  $head = ""; 
  $url_p = parse_url($url); 
  $host = $url_p["host"]; 
  if(!preg_match("/[0-9]*\.[0-9]*\.[0-9]*\.[0-9]*/",$host)){
    // a domain name was given, not an IP
    $ip=gethostbyname($host);
    if(!preg_match("/[0-9]*\.[0-9]*\.[0-9]*\.[0-9]*/",$ip)){
      //domain could not be resolved
      return -1;
    }
  }
  $port = intval($url_p["port"]); 
  if(!$port) $port=80;
  $path = $url_p["path"]; 
  //echo "Getting " . $host . ":" . $port . $path . " ...";

  $fp = fsockopen($host, $port, $errno, $errstr, 20); 

  if(!$fp) { 
    return false; 
    } else { 
    fputs($fp, "HEAD "  . $url  . " HTTP/1.1\r\n"); 
    fputs($fp, "HOST: " . $host . "\r\n"); 
    //fputs($fp, "User-Agent: http://www.example.com/my_application\r\n");
    fputs($fp, "Connection: close\r\n\r\n"); 
    $headers = ""; 
    while (!feof($fp)) { 
      $headers .= fgets ($fp, 128); 
      } 
    } 
  fclose ($fp); 

  //echo $errno .": " . $errstr . "<br />";
  $return = -2; 
  $arr_headers = explode("\n", $headers); 
  // echo "HTTP headers for <a href='" . $url . "'>..." . substr($url,strlen($url)-20). "</a>:";
  // echo "<div class='http_headers'>";
  foreach($arr_headers as $header) { 
    // if (trim($header)) echo trim($header) . "<br />";
    $s1 = "HTTP/1.1"; 
    $s2 = "Content-Length: "; 
    $s3 = "Location: "; 
    if(substr(strtolower ($header), 0, strlen($s1)) == strtolower($s1)) $status = substr($header, strlen($s1)); 
    if(substr(strtolower ($header), 0, strlen($s2)) == strtolower($s2)) $size   = substr($header, strlen($s2));  
    if(substr(strtolower ($header), 0, strlen($s3)) == strtolower($s3)) $newurl = substr($header, strlen($s3));  
    } 
  // echo "</div>";
  if(intval($size) > 0) {
    $return=intval($size);
  } else {
    $return=$status;
  }
  // echo intval($status) .": [" . $newurl . "]<br />";
  if (intval($status)==302 && strlen($newurl) > 0) {
    // 302 redirect: get HTTP HEAD of new URL
    $return=remote_file_size($newurl);
  }
  return $return;
}

function get_thumb_name($thumb){
  $path_parts = pathinfo($thumb);

  $f = $path_parts['dirname']."/".$path_parts['filename']."-th.".$path_parts['extension'];
  return $f;
}

function get_web_page( $url ,$show = 1)
{
  $options = array(
      CURLOPT_RETURNTRANSFER => true,     // return web page
      CURLOPT_HEADER         => false,    // don't return headers
      CURLOPT_FOLLOWLOCATION => true,     // follow redirects
      CURLOPT_ENCODING       => "",       // handle all encodings
      CURLOPT_USERAGENT      => "spider", // who am i
      CURLOPT_AUTOREFERER    => true,     // set referer on redirect
      CURLOPT_CONNECTTIMEOUT => 120,      // timeout on connect
      CURLOPT_TIMEOUT        => 120,      // timeout on response
      CURLOPT_MAXREDIRS      => 10,       // stop after 10 redirects
  );

  $ch      = curl_init( $url );
  curl_setopt_array( $ch, $options );
  $content = curl_exec( $ch );
  $err     = curl_errno( $ch );
  $errmsg  = curl_error( $ch );
  $header  = curl_getinfo( $ch );
  curl_close( $ch );

  $header['errno']   = $err;
  $header['errmsg']  = $errmsg;
  $header['content'] = $content;
  if($show){
    echo $content;
  }
  return $header;
}

function get_input_date($pefix = ""){
  echo "<select name = '".$pefix."day'>";
    for($i=1; $i<=31; $i++){
      echo "<option value = '".$i."'>".$i."</option>";
    }
  echo "</select>";

  echo "<select name = '".$pefix."month'>";
    for($i=1; $i<=12; $i++) {
      echo "<option value = '".$i."'>".get_month_name($i)."</option>";
    }
  echo "</select>";
  echo "<select name = '".$pefix."year'>";

    for($i=date("Y"); $i>date("Y")-80;$i--) {
      echo "<option value = '".$i."'>".$i."</option>";
    }
  echo "</select>";
}

function thaidate($date) {
  $time = explode(" ",$date);
  $t = explode(":",$time[1]);
  $field = explode("-",$time[0]);

  $field[1] = get_month_name($field[1]);

  if($field[2] == "01") $field[2] = "1";
  if($field[2] == "02") $field[2] = "2";
  if($field[2] == "03") $field[2] = "3";
  if($field[2] == "04") $field[2] = "4";
  if($field[2] == "05") $field[2] = "5";
  if($field[2] == "06") $field[2] = "6";
  if($field[2] == "07") $field[2] = "7";
  if($field[2] == "08") $field[2] = "8";
  if($field[2] == "09") $field[2] = "9";
  $field[0] = $field[0];

  return "$field[2] $field[1] $field[0] เวลา $t[0]:$t[1]";
}

function get_month_name($m){
    if($m == 1) return "มกราคม";
    if($m == 2) return "กุมภาพันธ์";
    if($m == 3) return "มีนาคม";
    if($m == 4) return "เมษายน";
    if($m == 5) return "พฤษภาคม";
    if($m == 6) return "มิถุนายน";
    if($m == 7) return "กรกฎาคม";
    if($m == 8) return "สิงหาคม";
    if($m == 9) return "กันยายน";
    if($m == 10) return "ตุลาคม";
    if($m == 11) return "พฤศจิกายน";
    if($m == 12) return "ธันวาคม";
  return "";
}

function get_month_name_en($m){
    if($m == 1) return "Jan";
    if($m == 2) return "Feb";
    if($m == 3) return "Mar";
    if($m == 4) return "Apr";
    if($m == 5) return "May";
    if($m == 6) return "Jun";
    if($m == 7) return "Jul";
    if($m == 8) return "Aug";
    if($m == 9) return "Sep";
    if($m == 10) return "Oct";
    if($m == 11) return "Nov";
    if($m == 12) return "Dec";
  return "";
}

function get_pic($email){
  $content = get_web_page("http://www.hi5.com/friend/processBrowseSearch.do?searchText=$email");
  $content= $content['content'];
  $tmp = split('<div class="friend-pic">',$content);
  $tmp = split('</div>',$tmp[1]);
  $pic = str_replace("href=\"","target = \"_blank\" href=\"http://www.hi5.com",$tmp[0]);
  return $pic;
}

function trimdilimiter($s){
  $s = trim($s);
  $l = substr($s,0,1);
  $r = substr($s,-1);

  if($l == ","){
    $s = substr($s,1);
  }

  if($r == ","){
    $s = substr($s,0,-1);
  }
  return $s;
}

function make_format($arr){
  $con = "";
  for($i = 0; $i < count($arr); $i++){
    $con .= $arr[$i].",";
  }

  return trimdilimiter($con);
}

function make_condition($arr, $field){

  if($arr != ""){
    $con = "WHERE $field = '";
    $con = $con.str_replace(",","' or $field = '",$arr);
    $con = $con."'";
  }else{
    $con = " WHERE 1 = 0 ";
  }

  return $con;
}

function check_node($arr, $id){

  $nodes = explode(",",$arr);
  for($i = 0; $i< count($nodes); $i++){
    if($id == $nodes[$i]){
      return $nodes[$i];
    }
  }
}

function add_node($arr, $id){
  $arr = $arr = ",".$id;
  return trimdilimiter($arr);
}

function remove_node($arr, $id){

  $nodes = explode(",",$arr);
  $newarr = "";
  for($i = 0; $i< count($nodes); $i++){
    if($id != $nodes[$i]){
      $newarr = add_node($newarr,$nodes[$i]);
    }
  }
  return $newarr;
}

function get_path($folder){

  $y = date("Y");
  $m = date("m");

  if( !file_exists($folder) ){
    mkdir($folder, 0777);
  }

  if( !file_exists($folder."/".$y) ){
    mkdir($folder."/".$y, 0777);
  }

  if( !file_exists($folder."/".$y."/".$m) ){
    mkdir($folder."/".$y."/".$m, 0777);
  }

  return $folder."/".$y."/".$m;
}

function get_url_path($path){
  $new = '';
  $p = explode("/",$path);
  for($i = 0; $i < count($p); $i++){
    if($p[$i] != ".." && $p[$i] != "."){
      $new .= $p[$i]."/";
    }
  }

  return substr($new, 0, -1);
}

function get_file_name($id, $file){

  $image_info = getimagesize($file);
  if( $image_info[2] == IMAGETYPE_JPEG ) {
     $ext = ".jpg";
  } elseif( $image_info[2] == IMAGETYPE_GIF ) {
     $ext = ".gif";
  } elseif( $image_info[2] == IMAGETYPE_PNG ) {
     $ext = ".png";
  }

  if($id == ""){
    $id = 0;
  }

  if(!file_exists($file)){
    $newfile = $id."-".time()."-".remote_file_size($file).$ext;
  }else{
    $newfile = $id."-".time()."-".filesize($file).$ext;
  }

  return $newfile;
}

function is_url($url){

  if(strrchr($url,"http://")){
    return true;
  }

  if(strrchr($url,"www.")){
    return true;
  }

  if(strrchr($url,".com")){
    return true;
  }

  return false;
}

function makethumb($src, $size = 100, $class = "picture",$alt = ""){

  $exists = false;
  if(is_url($src)){
    if(url_exists($src)){
      $exists = true;
    }
  }else{
    if(file_exists($src)){
      $exists = true;
    }
  }

  if($exists) {
    $img = getimagesize($src);
    if($img[0] > $img[1]){
      if($img[0] > $size){
        return "<img src = '$src' width = '".$size."' alt = '".$alt."' class = '$class' />";
      }
    }else{
      if($img[1] > $size){
        return "<img src = '$src' height = '".$size."' alt = '".$alt."' class = '$class' />";
      }
    }

    return "<img src = '$src' width = '".$img[0]."' height = '".$img[1]."' alt = '".$alt."' class = '$class' />";
  }

  return "<img src = 'nopic.png' style = 'width:".$size."px;height:".$size."px' alt = 'no thumb' class = '$class nopic' />";
}

function url_exists($url) {
    // Version 4.x supported
    $handle   = curl_init($url);
    if (false === $handle)
    {
        return false;
    }
    curl_setopt($handle, CURLOPT_HEADER, false);
    curl_setopt($handle, CURLOPT_FAILONERROR, true);  // this works
    curl_setopt($handle, CURLOPT_HTTPHEADER, Array("User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.15) Gecko/20080623 Firefox/2.0.0.15") ); // request as if Firefox   
    curl_setopt($handle, CURLOPT_NOBODY, true);
    curl_setopt($handle, CURLOPT_RETURNTRANSFER, false);
    $connectable = curl_exec($handle);
    curl_close($handle);  
    return $connectable;
}

function close(){
  echo "<html><body onLoad=\"javascript:self.close();\">";
  echo "</body></html>";
}

function close_and_refresh(){
   echo "<html><body onLoad=\"javascript:self.close();window.opener.location.reload();\">";
   echo "</body></html>";
}

function alert($msg) {
  echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>';
  echo "<script language = 'javascript'>";
  echo "alert('$msg')";
  echo "</script>";
}

function redirect($url) {
  echo "<html><head>";
  echo "<meta http-equiv='refresh' content='0; URL=$url'>";
  echo "</head></html>";
  exit;
}

function upload($file, $savefile){

  if ($_FILES[$file]['name'] != ''){

    if ($_FILES[$file]['error'] > 0) {
      echo 'Problem: ';
      switch ($_FILES[$file]['error']){
        case 1:
          echo 'File exceeded upload_max_filesize';
          break;
        case 2:
          echo 'File exceeded max_file_size';
          echo 'please resize picture to less than 600K then try again';
          break;
        case 3:
          echo 'File only partially uploaded';
          break;
        case 4:
          echo 'No file uploaded';
          break;
      }
      return false;
    }

    if (is_uploaded_file($_FILES[$file]['tmp_name'])){
      if (!move_uploaded_file($_FILES[$file]['tmp_name'], $savefile)){
        echo 'Problem: Could not move file to destination directory';
        return false;
      }else{
        return true;
      }
    }else{
      echo 'Problem: Possible file upload attack. Filename: '.$file;
      return false;
    }
  }

  return false;
}

function get_thai_date($date, $short = 0) {
  return date("d",$date). " " .get_month_name(date("m",$date), $short). " " . get_thai_year(date("Y",$date), $short);
}

function get_thai_year($y,$short = 0){
  if($short){
    return substr($y + 543, 2, 2);
  }
  return $y + 543;
}

function setpage($c){

  $max = ceil($c/PAGE);

  echo __l('page') ." &nbsp;&nbsp;";

  for($i = 1; $i <= $max; $i++){
    echo  " | <a href = '?page=$i'>&nbsp;&nbsp;" . $i . "&nbsp;&nbsp;</a>";
  }

  if(!isset($_GET['page'])){ //Nawattapon XAMPP Error
    // $_GET['page'] = 1;
    //$start = 1; // Nawattapon 
    $start = 0;
  }else{
    $start = ($_GET['page']-1)*PAGE;
  }

  return $start;
}

function group_date($s, $e){

  if($e - $s < DAY) {
    return date("d M Y",$s);
  }elseif(date("m",$s) == date("m",$e)){
    return date("d", $s) . " - ". date("d", $e)." ". date("M Y",$s);
  }elseif(date("y",$s) == date("y",$e)){
    return date("d M", $s) . " - ". date("d M", $e)." ". date("Y",$s);
  }else{
    return date("d M Y", $s) . " - ". date("d M Y", $e);
  }

}

function group_time($s, $e){
  if($s != "")
    echo date("H:i",$s);
  if($e != "")
    echo " - ".date("H:i",$e);
}

function get_status($s,$c){
  if($s==$c){
    echo "checked";
  }
}

//Nawattapon
function remove_dir($dir){
  if(is_dir($dir)){
    $dir = (substr($dir, -1) != "/")? $dir."/":$dir;
    $openDir = opendir($dir);
    while($file = readdir($openDir)){
      if(!in_array($file, array(".", ".."))){
        if(!is_dir($dir.$file)){
          unlink($dir.$file);
        }else{
          remove_dir($dir.$file);
        }
      }
    }
    closedir($openDir);
    rmdir($dir);
  }
}

function utf8_to_tis620($string)
	{
		$str = $string;
		$res = "";
		for ($i = 0; $i < strlen($str); $i++) {
		  if (ord($str[$i]) == 224) {
			$unicode = ord($str[$i+2]) & 0x3F;
			$unicode |= (ord($str[$i+1]) & 0x3F) << 6;
			$unicode |= (ord($str[$i]) & 0x0F) << 12;
			$res .= chr($unicode-0x0E00+0xA0);
			$i += 2;
		  } else {
			$res .= $str[$i];
		  }
		}
		return $res;
	}
        
function substr_utf8( $str, $start_p , $len_p){
  return preg_replace( '#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$start_p.'}'.
  '((?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$len_p.'}).*#s',
  '$1' , $str );
};
?>